package com.cn.wanxi.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/back/*")//需要拦截前端访问后台的地址，*表示全部拦截
public class MyFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
//        1.乱码处理
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String username = (String) request.getSession().getAttribute("username");
//        如果用户名为空，则跳转到登录页面，否则放行
        if (username == null) {

            response.sendRedirect("/html/login.html");
        } else {
            chain.doFilter(request, response);
        }
    }
}
